import axios from 'axios'
import { ElMessage } from 'element-plus'
import { userLoadingStore } from '@/stores'
import VueCookie from 'vue-cookie'
import router from '@/router'

export const _axios = axios.create({
  baseURL: 'http://127.0.0.1:8080',
})

let userLoading = userLoadingStore()

// // 请求拦截器
// _axios.interceptors.request.use(config => {
// 	const token = VueCookie.get('token')
// 	if (token) {
// 		config.headers.token = token
// 	}
// 	return config
// }, error => {
// 	return Promise.reject(error)
// })

// axios.js 或类似文件
const instance = axios.create({
  baseURL: 'http://127.0.0.1:8080',
  timeout: 10000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 如果是POST/PUT/PATCH请求且没有设置Content-Type，默认设置为application/json
    if (['post', 'put', 'patch'].includes(config.method?.toLowerCase()) && 
        !config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/json';
    }
    
    // 可以在这里添加token等认证信息
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);


// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    // 统一错误处理
    return Promise.reject(error);
  }
);

export default instance;


// 核心请求函数 - 同时支持回调和 Promise
export const request = (url, method, params, callbackOrContentType, contentType) => {
  // 参数兼容性处理
  let callback = null
  let actualContentType = 'form'

  // 判断第4个参数是函数还是字符串
  if (typeof callbackOrContentType === 'function') {
    callback = callbackOrContentType
    actualContentType = contentType || 'form'
  } else if (typeof callbackOrContentType === 'string') {
    actualContentType = callbackOrContentType
  }

  console.log('🔍 Request Debug:', { url, method, params, actualContentType })

  const axiosConfig = {
    url,
    method,
  }

  // 配置请求体
  if (method === 'post' || method === 'put') {
    if (actualContentType === 'json') {
      console.log('🔍 使用 JSON 格式')
      axiosConfig.data = params
      axiosConfig.headers = { 'Content-Type': 'application/json' }
    } else {
      console.log('🔍 使用 FormData 格式')
      const formData = new FormData()
      for (const key in params) {
        formData.append(key, params[key])
      }
      axiosConfig.data = formData
    }
  } else if (method === 'delete') {
    axiosConfig.params = params
  } else {
    axiosConfig.params = params
  }

  console.log('🔍 Axios Config:', axiosConfig)

  userLoading.setLoading(true)

  const promise = _axios
    .request(axiosConfig)
    .then((response) => {
      console.log('🔍 完整响应:', response.data)

      if (response.data.code === 200) {
        if (response.data.message) {
          ElMessage.success(response.data.message)
        }

        // ✅ 修改点：优先返回 content，否则返回整个 data
        const result = response.data.content !== undefined ? response.data.content : response.data

        // 如果有回调函数，执行回调
        if (callback) {
          callback(result)
        }

        return result
      } else {
        ElMessage.error(response.data.message)
        if (response.data.code === 401) {
          router.push({ path: '/' })
        }
        throw new Error(response.data.message)
      }
    })
    .catch((error) => {
      console.dir(error)
      ElMessage.error(error.message || '请求失败')
      throw error
    })
    .finally(() => {
      userLoading.setLoading(false)
    })

  // 如果没有回调函数，则返回 Promise
  return callback ? undefined : promise
}

// GET 请求
export const get = (url, params, callback) => {
  return request(url, 'get', params, callback)
}

// POST 请求
export const post = (
  url,
  params,
  callbackOrFormObj,
  formObjOrContentType,
  contentType = 'form',
) => {
  let callback = null
  let formObj = null
  let actualContentType = 'form'

  if (typeof callbackOrFormObj === 'function') {
    callback = callbackOrFormObj
    formObj = formObjOrContentType
    actualContentType = contentType
  } else {
    formObj = callbackOrFormObj
    actualContentType = typeof formObjOrContentType === 'string' ? formObjOrContentType : 'form'
  }

  console.log('🔍 Post Debug:', { url, params, actualContentType, formObj })

  if (formObj) {
    if (callback) {
      formObj.value.validate((valid) => {
        if (valid) {
          request(url, 'post', params, callback, actualContentType)
        }
      })
    } else {
      return new Promise((resolve, reject) => {
        formObj.value.validate((valid) => {
          if (valid) {
            request(url, 'post', params, actualContentType).then(resolve).catch(reject)
          } else {
            reject(new Error('表单验证失败'))
          }
        })
      })
    }
  } else {
    return request(
      url,
      'post',
      params,
      callback || actualContentType,
      callback ? actualContentType : undefined,
    )
  }
}

// POST JSON
export const postJson = (url, params, callbackOrFormObj, formObj) => {
  console.log('🔍 PostJson Debug:', { url, params })
  if (typeof callbackOrFormObj === 'function') {
    return post(url, params, callbackOrFormObj, formObj, 'json')
  } else {
    return post(url, params, callbackOrFormObj, 'json')
  }
}

// PUT 请求
export const put = (url, params, formObj = null) => {
  console.log('🔍 Put Debug:', { url, params })
  if (formObj) {
    return new Promise((resolve, reject) => {
      formObj.value.validate((valid) => {
        if (valid) {
          request(url, 'put', params, 'json').then(resolve).catch(reject)
        } else {
          reject(new Error('表单验证失败'))
        }
      })
    })
  } else {
    return request(url, 'put', params, 'json')
  }
}

// DELETE 请求
export const del = (url, params = {}) => {
  console.log('🔍 Delete Debug:', { url, params })
  return request(url, 'delete', params)
}

// 提交多个表单
export const submitMultipleForms = async (url, params, callbackOrFormObjs, formObjs) => {
  let callback = null
  let actualFormObjs = []

  if (typeof callbackOrFormObjs === 'function') {
    callback = callbackOrFormObjs
    actualFormObjs = formObjs || []
  } else {
    actualFormObjs = callbackOrFormObjs || []
  }

  try {
    let isValid = true

    if (actualFormObjs.length > 0) {
      const validationPromises = actualFormObjs.map((formObj) => {
        return new Promise((resolve) => {
          formObj.value.validate((valid) => {
            if (!valid) isValid = false
            resolve(valid)
          })
        })
      })

      await Promise.all(validationPromises)
    }

    if (isValid) {
      if (callback) {
        postJson(url, params, callback)
      } else {
        return postJson(url, params)
      }
    } else {
      throw new Error('表单验证失败')
    }
  } catch (error) {
    console.error('Error during form validation:', error)
    throw error
  }
}

// 添加delete方法
export const deleteRequest = (url, params, callback) => {
  request(url, 'delete', params, callback)
}

// 工具函数
export const isPromiseMode = (callback) => !callback
